/* 后端地址 */
const API_BASE = "http://localhost:5001";

/* Canvas 配置 */
const canvas   = document.getElementById("canvas");
const ctx      = canvas.getContext("2d");
const BOARD_W  = 20;   // 格子宽
const BOARD_H  = 15;   // 格子高
const CELL     = Math.min(canvas.width / BOARD_W, canvas.height / BOARD_H);

/* 右侧聊天记录 DOM */
const chatLog  = document.getElementById("chatLog");

/* 工具：添加一行聊天记录 */
const chatMax  = 20;
function pushChat(text){
  const div = document.createElement("div");
  div.className = "msg";
  div.textContent = text;
  chatLog.prepend(div);
  while(chatLog.children.length > chatMax){
    chatLog.removeChild(chatLog.lastChild);
  }
}

/* 工具：绘制单格 */
function drawCell(x,y,color="#0f0"){
  ctx.fillStyle=color;
  ctx.fillRect(x*CELL, y*CELL, CELL-1, CELL-1);
}

/* 根据后端数据绘制 */
function render(state){
  ctx.clearRect(0,0,canvas.width,canvas.height);
  state.snake.forEach((pt,i)=>drawCell(...pt, i===0?"#0ff":"#0a0"));
  drawCell(...state.food, "#f00");
}

/* 递归式主循环：等上一次完成后再等 200 ms 发起下一次 */
const TICK_MS = 200;   // 可调
async function loop(){
  try{
    const res  = await fetch(`${API_BASE}/step`, {method:"POST"});
    const data = await res.json();
    render(data);
    pushChat(`Step → ${data.next_action.toUpperCase()} | Score ${data.score}`);
    if(data.game_over){
      pushChat("💀 Game Over — 已重新开始");
    }
  }catch(e){
    console.error(e);
    pushChat("❌ 网络或后端错误");
  }finally{
    setTimeout(loop, TICK_MS);   // 关键：等待后才下一次
  }
}

/* 启动 */
loop();
//tick();
//setInterval(tick, 200);